问题描述(难度中等-494)
You are given a list of non-negative integers, a1, a2, …, an, and a target, S. Now you have 2 symbols +
and -
. For each integer, you should choose one from +
and -
as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
1 | Input: nums is [1, 1, 1, 1, 1], S is 3. |
Note:
- The length of the given array is positive and will not exceed 20.
- The sum of elements in the given array will not exceed 1000.
- Your output answer is guaranteed to be fitted in a 32-bit integer.
方法一:Using Recursive
通过递归,递归有重复的子结构。可以通过DP改善。
1 | package P494; |
方法二:Using DP
通过dp规避重复子问题。
1 | package P494; |
对应的存储结构图:
方法三:Using DFS
回溯可以通过递归的方式去实现。这里通过map保存下重复的运算。
1 | public class Solution { |